import { message } from '@/utils/message'
import { reactive, ref, toRefs, watch } from 'vue'
import { useDicts } from '@/utils/dict'
import type { FormInstance } from 'element-plus'
import { addRole, updateRole } from '@/api/system/role'
import { useGlobal } from '@pureadmin/utils'

export function useRoleForm(props, emit) {
  const { $config } = useGlobal<GlobalPropertiesApi>()
  const data = reactive({
    rules: {
      roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
      roleKey: [{ required: true, message: '权限字符不能为空', trigger: 'blur' }],
      roleSort: [{ required: true, message: '角色顺序不能为空', trigger: 'blur' }],
    },
  })
  const { rules } = toRefs(data)
  const title = ref(props.title)
  const formData = ref(props.data)
  const menuOptions: any = ref([props.menuOptions])
  const menuRef = ref(null)
  const menuExpand = ref(false)
  const menuNodeAll = ref(false)
  const formVisible = ref(false)
  const checkedKeys = ref([])
  const ruleFormRef = ref<FormInstance>()
  const { sys_normal_disable } = useDicts('sys_normal_disable')

  /** 树权限（展开/折叠）*/
  function handleCheckedTreeExpand(value, type) {
    if (type == 'menu') {
      const treeList = menuOptions.value
      for (let i = 0; i < treeList.length; i++) {
        menuRef.value.store.nodesMap[treeList[i].id].expanded = value
      }
    }
  }

  /** 树权限（全选/全不选） */
  function handleCheckedTreeNodeAll(value, type) {
    if (type == 'menu') {
      menuRef.value.setCheckedNodes(value ? menuOptions.value : [])
    }
  }

  /** 树权限（父子联动） */
  function handleCheckedTreeConnect(formData, value, type) {
    if (type == 'menu') {
      formData.menuCheckStrictly = value ? true : false
    }
  }

  /** 所有菜单节点数据 */
  function getMenuAllCheckedKeys() {
    // 目前被选中的菜单节点
    const checkedKeys = menuRef.value.getCheckedKeys()
    // 半选中的菜单节点
    const halfCheckedKeys = menuRef.value.getHalfCheckedKeys()
    checkedKeys.unshift(...halfCheckedKeys)
    return checkedKeys
  }

  /** 提交表单  */
  async function submitForm(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.validate((valid) => {
      if (valid) {
        if (formData.value.osType !== 0) {
          formData.value.osType = $config.OSType
        }
        if (formData.value.roleId != undefined) {
          formData.value.menuIds = getMenuAllCheckedKeys()
          updateRole(formData.value).then(() => {
            message('提交成功', { type: 'success' })
            formVisible.value = false
            emit('refresh')
            resetForm(formEl)
          })
        } else {
          formData.value.menuIds = getMenuAllCheckedKeys()
          addRole(formData.value).then(() => {
            formData.value.menuIds = getMenuAllCheckedKeys()
            message('新增成功', { type: 'success' })
            formVisible.value = false
            emit('refresh')
            resetForm(formEl)
          })
        }
      }
    })
  }

  /* 关闭弹窗 */
  function closeDialog() {
    formVisible.value = false
    resetForm(ruleFormRef.value)
  }

  /** 重置表单  */
  function resetForm(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.resetFields()
  }

  watch(
    () => formVisible.value,
    (val) => {
      emit('update:visible', val)
    }
  )

  watch(
    () => props.visible,
    (val) => {
      formVisible.value = val
    }
  )

  watch(
    () => props.title,
    (val) => {
      title.value = val
    }
  )

  watch(
    () => props.data,
    (val) => {
      formData.value = val
    }
  )

  watch(
    () => props.menuOptions,
    (val) => {
      menuOptions.value = val
    }
  )

  watch(
    () => props.checkedKeys,
    (val) => {
      checkedKeys.value = val
    }
  )

  return {
    rules,
    title,
    menuRef,
    formData,
    formVisible,
    menuOptions,
    menuExpand,
    menuNodeAll,
    ruleFormRef,
    sys_normal_disable,
    checkedKeys,
    submitForm,
    closeDialog,
    handleCheckedTreeNodeAll,
    handleCheckedTreeExpand,
    handleCheckedTreeConnect,
  }
}
